package com.example.chongwushangcheng.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.chongwushangcheng.model.PetPost;

import java.util.List;

/**
 * 宠物交流帖子列表适配器
 */
public class PetPostAdapter extends RecyclerView.Adapter<PetPostAdapter.ViewHolder> {

    private List<PetPost> postList;
    private Context context;
    private OnItemClickListener listener;

    public PetPostAdapter(Context context, List<PetPost> postList) {
        this.context = context;
        this.postList = postList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_pet_post, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        PetPost post = postList.get(position);
        
        // 设置帖子图片
        holder.ivPostImage.setImageResource(post.getImageResId());
        
        // 设置帖子标题
        holder.tvPostTitle.setText(post.getTitle());
        
        // 设置用户头像文字（第一个字符）
        holder.tvUserAvatar.setText(post.getUserAvatar());
        
        // 设置用户名
        holder.tvUserName.setText(post.getUserName());
        
        // 设置浏览次数
        holder.tvViewCount.setText(String.valueOf(post.getViewCount()));
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(post, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(PetPost post, int position);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPostImage;
        TextView tvPostTitle;
        TextView tvUserAvatar;
        TextView tvUserName;
        TextView tvViewCount;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPostImage = itemView.findViewById(R.id.iv_post_image);
            tvPostTitle = itemView.findViewById(R.id.tv_post_title);
            tvUserAvatar = itemView.findViewById(R.id.tv_user_avatar);
            tvUserName = itemView.findViewById(R.id.tv_user_name);
            tvViewCount = itemView.findViewById(R.id.tv_view_count);
        }
    }
} 